/* eslint-disable no-cond-assign */
/* eslint-disable react/sort-comp */
import React, { Component } from "react";
import { Button, Form, Input, Checkbox, Switch, Spin, Select, Row, Col, Table, InputNumber, Icon, Popover } from "antd";
import { messages } from "share/common";
import { connect } from "react-redux";
import Priority from "components/template/priority";
import "styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss";
import NewConsumerServer from "../new-consumer-server";
import { message } from "antd/lib/index";
import ConsumerUtil from "../consumer-util";
import menuRoute from "routes/menuRoute";

const FormItem = Form.Item;
const Group = Checkbox.Group;
const { Option } = Select;

const getMealTypesRenderFn = (options, type, context) => (text, value, idx) => (
  <Select
    placeholder={messages("common.select") /*请选择*/}
    onChange={(value) => context.onChange(value, idx, type)}
    value={context.state.regulationDatas[idx][type]}
  >
    {options}
  </Select>
);

@Form.create()
class ElemeEditFrame extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editData: {},
      loading: false,
      isNew: false,
      priDefalultValue: {},
      mealTypeOptions: [],
      regulationDatas: [
        {
          hlyCompanyOid: "",
          hlyTenantCode: props.tenant.id,
          tmcRegulationId: "",
          id: "",
        },
      ],
      travelPolicy: menuRoute.getRouteItem("travel-standard", "key"),
    };

    this.isLock = false;
    this.approvalOptions = [
      {
        label: messages("supplier-1.key764") /*用餐*/,
        value: "useMeal",
      },
    ];
    this.mealModeOptions = [
      { value: "standard", code: "standard", messageKey: messages("supplier-1.key816") /*标准*/ },
      { value: "mealSupplement", code: "mealSupplement", messageKey: messages("supplier-1.key817") /*餐补*/ },
    ];
  }

  static contextTypes = {
    router: React.PropTypes.object,
  };

  getColumns = (mealTypeOptions, mealModeOptions) => {
    const { regulationDatas } = this.state;
    const columns = [
      {
        title: messages("supplier-1.key818") /*用餐类型*/,

        dataIndex: "hlyMealType",
        key: "hlyMealType",
        render: getMealTypesRenderFn(this.renderOption(mealTypeOptions), "hlyMealType", this),
      },
      {
        title: messages("supplier-1.key819") /*制度ID*/,
        dataIndex: "tmcRegulationId",
        key: "tmcRegulationId",
        render: (val, row, idx) => (
          <Input
            placeholder={messages("common.please.input") /*请输入*/}
            value={regulationDatas[idx].tmcRegulationId}
            onChange={(e) => this.onChange(e.target.value, idx, "tmcRegulationId")}
          />
        ),
      },
      {
        title: messages("supplier-1.key820") /*用餐模式*/,
        dataIndex: "hlyDiningMode",
        key: "hlyDiningMode",
        render: getMealTypesRenderFn(this.renderOption(mealModeOptions), "hlyDiningMode", this),
      },
      {
        title: (
          <div style={{ display: "flex" }}>
            <div style={{ marginRight: "0.5em" }}>{messages("supplier-1.key835") /*可用次数*/}</div>
            <Popover
              content={
                <p className="eleme-jump-tip">
                  {messages("supplier-1.key836") /*“可用次数”说明：审批单中对应用餐类型可使用次数*/}
                </p>
              }
            >
              <Icon type="info-circle-o" style={{ lineHeight: " unset" }} />
            </Popover>
          </div>
        ),
        dataIndex: "hlyDiningNumber",
        key: "hlyDiningNumber",
        render: (val, row, idx) => (
          <InputNumber
            placeholder={messages("common.please.input") /*请输入*/}
            value={regulationDatas[idx].hlyDiningNumber}
            onChange={(e) => this.onChange(e, idx, "hlyDiningNumber")}
          />
        ),
      },
      {
        title: messages("common.operation") /*操作*/,
        dataIndex: "operation",
        render: (...args) => {
          const [row, content, idx] = args;
          const { regulationDatas } = this.state;
          return <div>{<a onClick={() => this.onDelete(idx)}>{messages("common.delete") /*删除*/}</a>}</div>;
        },
      },
    ];
    return columns;
  };

  onChange = (...args) => {
    const [value, idx, type] = args;
    const regulationDatas = this.state.regulationDatas;
    let mealType;
    if (type === "hlyMealType" && (mealType = this.mealTypeOptions.find((item) => item.id === value))) {
      regulationDatas[idx].hlyMealType = mealType.id;
      regulationDatas[idx].id = mealType.id;
    } else {
      regulationDatas[idx][type] = value;
    }

    this.setState({ regulationDatas });
  };

  //渲染用餐类型Option
  renderOption = (data) => {
    if (data && data.length) {
      return data.map((item) => {
        return (
          <Option value={item.value} key={item.code}>
            {item.messageKey}
          </Option>
        );
      });
    }
    return null;
  };

  componentWillMount() {
    const { params, tenant } = this.props;
    const initValue = {
      levelCode: "COMPANY",
      companyOID: params.companyOid,
      levelOrgName: params.name,
    };

    this.setState(
      {
        editData: params,
        isNew: !params.name,
        priDefalultValue: initValue,
      },
      this.props.form.resetFields
    );
    if (params.name) {
      this.setState({
        regulationDatas: params.elemeRegulationDetailParams
          ? params.elemeRegulationDetailParams.map((item) => ({ ...item, rowKey: Math.random() }))
          : [],
      });
    }
    params.companyOid && this.getMealTypeList({ companyOID: params.companyOid, page: 0, size: 10 });
  }

  getMealTypeList = (params) => {
    this.setState({ mealtypesLoading: false });
    NewConsumerServer(this)
      .getMealType(params)
      .then((res) => {
        if (res.data) {
          const mealTypeOptions = res.data.map(({ id, name }) => {
            this.mealTypeOptions = res.data;
            return { value: id, code: id, messageKey: name };
          });
          this.setState({ mealTypeOptions });
          this.setState({ mealtypesLoading: true });
        } else {
          message.error(messages("supplier-1.key821") /*获取用餐类型失败*/);
        }
      });
  };

  onPriorityChange = (values) => {
    const { companyOID, page = 0, size = 10 } = values;
    const params = { companyOID, page, size };
    const { regulationDatas } = this.state;
    const newRegulationDatas = regulationDatas.map((regulationData) => {
      return {
        ...regulationData,
        ...{ hlyCompanyOid: values.companyOID, hlyTenantCode: this.props.tenant.id },
      };
    });
    this.setState({
      priDefalultValue: values,
      regulationDatas: newRegulationDatas,
    });
    this.getMealTypeList(params);
  };

  onCancelEdit = () => {
    this.props.close();
    this.props.form.resetFields();
  };

  onSubmitEdit = () => {
    if (this.isLock) {
      return;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { priDefalultValue, isNew, editData, regulationDatas } = this.state;
        const authData = JSON.parse(JSON.stringify(priDefalultValue));
        const { tenant } = this.props;
        if (!authData) {
          message.error(messages("supplier-1.key185") /*请填写所属组织*/);
          return;
        }
        if (!authData.distribution && authData.levelCode != "COMPANY") {
          message.error(messages("supplier-1.key186") /*启用公司不支持通用*/);
          return;
        }
        if (authData.levelCode == "COMPANY" && !authData.companyOID) {
          message.error(messages("supplier-1.key187") /*请填写公司*/);
          return;
        }

        const hlyMealTypes = regulationDatas.map(({ hlyMealType }) => hlyMealType);
        if (new Set(hlyMealTypes).size !== hlyMealTypes.length) {
          message.info(messages("supplier-1.key864") /*不可选择重复的用餐类型*/);
          return;
        }
        const pri = {
          ...authData,
          companies: authData.distribution ? authData.distribution.companies.map((item) => item.id) : [],
        };
        delete pri.distribution;

        let upParams = Object.assign({}, values, pri);

        upParams.hlyTravelStatus = false; //upParams.useMeal.length!!;
        upParams.hlyTenantCode = tenant.id;
        upParams.hlyTenantName = tenant.tenantName;
        upParams.hlyConfigLevel = 1001;
        upParams.syncDepartment = false;
        upParams.elemeRegulationDetailParams = regulationDatas;
        upParams.name = upParams.levelOrgName;
        upParams.companyOid = upParams.companyOID;

        if (!isNew) {
          upParams = Object.assign({}, editData, upParams);
        }
        delete upParams.useMeal;
        delete upParams.companies;
        delete upParams.levelCode;
        delete upParams.levelOrgId;
        delete upParams.levelOrgName;
        delete upParams.companyOID;

        this.isLock = true;
        NewConsumerServer(this)
          //这里到时候换接口
          .saveEleme(upParams)
          .then((res) => {
            this.isLock = false;
            if (!res.data.passFlag && res.data.message) {
              message.error(res.data.message);
            } else {
              this.props.close(true);
            }
          });
      }
    });
  };

  onJump = () => {
    const { travelPolicy } = this.state;
    this.context.router.push(`${travelPolicy.url}?tab=dining`);
  };

  onAdd = () => {
    const { regulationDatas } = this.state;
    regulationDatas.push({
      hlyCompanyOid: this.state.priDefalultValue.companyOID,
      hlyTenantCode: this.props.tenant.id,
      tmcRegulationId: "",
      id: "",
    });
    this.setState({ regulationDatas });
  };

  onDelete = (idx) => {
    const { regulationDatas } = this.state;
    regulationDatas.splice(idx, 1);
    this.setState({ regulationDatas });
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const {
      editData,
      loading,
      isNew,
      priDefalultValue,
      regulationDatas,
      mealTypeOptions,
      tableLoading,
      mealtypesLoading,
    } = this.state;
    const columns = this.getColumns(mealTypeOptions, this.mealModeOptions);

    const initialApproval = [];
    this.approvalOptions.forEach(({ value }) => {
      if (editData[value]) {
        initialApproval.push(value);
      }
    });
    const formLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14 },
    };

    return (
      <div className="edit-frame">
        <Spin spinning={loading}>
          <Form className="new-form">
            <FormItem label={messages("common.column.status") /*状态*/} {...formLayout}>
              {getFieldDecorator("hlyConfigStatus", {
                initialValue: editData.hlyConfigStatus || true,
                valuePropName: "checked",
              })(<Switch />)}
            </FormItem>
            <Priority
              top="COMPANY"
              formItemLayout={formLayout}
              disabledTop={!isNew}
              companyProps={{ disabled: !isNew }}
              defaultValue={isNew ? "" : priDefalultValue}
              onChange={this.onPriorityChange}
            />
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key765") /*规则条件*/}</div>
            </h3>
            <FormItem label={messages("supplier-1.key766") /*客户编码*/} {...formLayout}>
              {getFieldDecorator("consumerNo", {
                initialValue: editData.consumerNo || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input placeholder={messages("common.please.input") /*请输入*/} />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key767") /*客户秘钥*/} {...formLayout}>
              {getFieldDecorator("consumerSecret", {
                initialValue: editData.consumerSecret || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input placeholder={messages("common.please.input") /*请输入*/} />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key768") /*企业ID*/} {...formLayout}>
              {getFieldDecorator("enterpriseId", {
                initialValue: editData.enterpriseId || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input placeholder={messages("common.please.input") /*请输入*/} />)}
            </FormItem>

            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key770") /*制度ID配置*/}</div>
            </h3>
            <div className="eleme-tip-line">
              <div className="eleme-jump-tip">
                {messages("supplier-1.key822") /*需先至【差旅标准】新增用餐类型，点击*/}
                <a onClick={this.onJump}>{messages("supplier-1.key823") /*配置用餐类型*/}</a>
              </div>
              <div onClick={this.onAdd}>
                <Icon className="add-icon" type="plus-circle-o" />
                <a>{messages("supplier-1.key666")}</a>
              </div>
            </div>

            {(mealtypesLoading || isNew) && (
              <Table
                rowKey={(row) => row.rowKey}
                style={{ padding: "12px 32px" }}
                pagination={false}
                columns={columns}
                dataSource={regulationDatas}
              />
            )}
          </Form>
        </Spin>
        <br />
        <br />
        <br />
        <br />
        <div className="affix-bottom">
          <Button type="primary" loading={loading} onClick={this.onSubmitEdit}>
            {messages("common.ok") /*确定*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancelEdit}>{messages("common.cancel") /*取消*/}</Button>
        </div>
      </div>
    );
  }
}

ElemeEditFrame.getEditData = (record) => {
  const params = JSON.parse(JSON.stringify(record));
  return params;
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  };
}

export default connect(mapStateToProps)(ElemeEditFrame);
